package com.example.botdemo02.client;

import com.alibaba.fastjson.JSONObject;

import com.example.botdemo02.common_enum.BotActionEnum;
import com.example.botdemo02.enity.common.Count;
import com.example.botdemo02.enity.qq.Friend;
import com.example.botdemo02.enity.qq.Message;
import com.example.botdemo02.enity.qq.Request;

import com.example.botdemo02.gpt.GptUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.springframework.context.ApplicationContext;

import javax.websocket.*;
import java.io.IOException;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@ClientEndpoint
@Slf4j
public class BotClient {
    private Session session;
    public static BotClient instance;
    public static boolean isOpen = false;
    /*
     * 提供一个spring context上下文(解决方案)
     */
    private static ApplicationContext applicationContext;
    public static Count count;
    //    单例模式，只生成一个客户端连接对象
    private BotClient(String url) {
        try {
            session = ContainerProvider.getWebSocketContainer().connectToServer(this, URI.create(url));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static void setApplicationContext(ApplicationContext applicationContext) {
       BotClient.applicationContext = applicationContext;
       count = applicationContext.getBean(Count.class);
    }

    /**
     * 创建连接
     * @param url
     * @return
     */
    public synchronized static boolean connect(String url) {
        instance = new  BotClient(url);
        return true;
    }

    /**
     * 连接前处理
     * @param session
     */
    @OnOpen
    public void onOpen(Session session) {
        isOpen = true;
        log.info("连接成功！");
    }

    /**
     * 连接关闭处理
     * @param session
     */
    @OnClose
    public void onClose(Session session) {
        isOpen = false;
        log.info("连接关闭！");
    }

    /**
     * 错误时处理
     * @param session
     * @param throwable
     */
    @OnError
    public void onError(Session session, Throwable throwable) {
        log.info("连接错误！");
    }

    /**
     * 接收到消息时处理
     * @param message
     */
    @OnMessage
    public void onMessage(String message) {
//        加好友
        if (message.contains("\"request_type\":\"friend\"")) {
            sendFriend(message);
        }
//        私信
        if (message.contains("\"post_type\":\"message\"") && message.contains("\"message_type\":\"private\"")) {
            sendMsg(message);
        }
//        群消息
        if (message.contains("\"post_type\":\"message\"")&& message.contains("\"message_type\":\"group\""))  {
            sendGroupMsg(message);
        }
    }

    /**
     * 好友请求
     */
    private synchronized void sendFriend(String msg) {
        Friend parseObject = JSONObject.parseObject(msg, Friend.class);
        log.info("收到好友请求：" + parseObject.getUser_id() + ",验证消息：" + parseObject.getComment());
        Request<Object> paramsRequest = new Request<>();
        paramsRequest.setAction(BotActionEnum.ADD_FRIEND_ACTION.getAction());
        Map<String, Object> params = new HashMap<>();
        params.put("flag", parseObject.getFlag());
        if (parseObject.getComment().equals(count.getAuthor())) {
            params.put("approve", true);
            log.info("已同意好友请求：" + parseObject.getUser_id());
        } else {
            params.put("approve", false);
            log.info("已拒绝好友请求：" + parseObject.getUser_id());
        }
        paramsRequest.setParams(params);
        instance.session.getAsyncRemote().sendText(JSONObject.toJSONString(paramsRequest));
    }
    /**
     * 群消息
     */
    public synchronized  void sendGroupMsg(String msg) {
        System.out.println(msg);
        Message parseObject = JSONObject.parseObject(msg, Message.class);
        log.info("收到群消息" + parseObject.getGroupId() + "的消息，发送者"+parseObject.getUserId()+"消息："
                + parseObject.getMessage()+"消息id:"+parseObject.getMessageId()
        );
        System.out.println(parseObject.getMessage());
        String mes = parseObject.getMessage();
        if(mes.contains("[CQ:at,qq="+count.getBot_count()+"]")) {
            Request<Object> paramsRequest = new Request<>();
            paramsRequest.setAction(BotActionEnum.SEND_GROUP_MESSAGE.getAction());
            Map<String, Object> params = new HashMap<>();
            params.put("group_id", parseObject.getGroupId());
            String ai = AiOne(parseObject.getMessage(),parseObject.getMessageId());
            if (ai == null) {
                ai = "宝，回复失败!重新试试吧!";
            }
            params.put("message", ai);
            params.put("message_type", "group");
            params.put("auto_escape", false);
            paramsRequest.setParams(params);
            msg = JSONObject.toJSONString(paramsRequest);
            //        回复
            instance.session.getAsyncRemote().sendText(msg);
        }

    }
    /**
     * 私信好友消息
     */
    public synchronized void sendMsg(String msg) {
        Message parseObject = JSONObject.parseObject(msg, Message.class);
        log.info("收到好友" + parseObject.getUserId() + "的消息：" + parseObject.getMessage());
        System.out.println("消息："+parseObject.getMessage());
        Request<Object> paramsRequest = new Request<>();
        paramsRequest.setAction(BotActionEnum.SEND_PRIVATE_MESSAGE.getAction());
        Map<String, Object> params = new HashMap<>();
        params.put("user_id", parseObject.getUserId());
        String ai = AiOne(parseObject.getMessage(),null);
        if (ai == null) {
            ai = "宝，回复失败!重新试试吧!";
        }
        params.put("message", ai);
        params.put("message_type", "private");
        params.put("auto_escape", false);
        paramsRequest.setParams(params);
        msg = JSONObject.toJSONString(paramsRequest);
//        回复
        instance.session.getAsyncRemote().sendText(msg);
    }
    public  String AiOne(String sendMsg,String mes_id) {
        CloseableHttpClient httpClient = null;
        try {
             httpClient= HttpClientBuilder.create().build();
            GptUtils gptUtils = applicationContext.getBean(GptUtils.class);
            if(sendMsg.contains("画一幅图:")){
                log.info("进入到绘图......");
                String initBody = gptUtils.getImageURl(httpClient,sendMsg);
                if(Objects.isNull(mes_id)){
                  String body =initBody;
                    log.info("body:"+body);
                  return body;
                }
                 String body = "[CQ:reply,id="+mes_id+"]"+initBody;
                log.info("body:"+body);
                return body;
            }
            String initBody = gptUtils.getAnswer(httpClient,sendMsg);
            String body = null;
            if(Objects.isNull(mes_id)){
                 body=initBody;
                log.info("body:"+body);
                return body;
            }
            body = "[CQ:reply,id="+mes_id+"]"+initBody;
            log.info("body:"+body);
                return body;
        } catch (Exception e) {
            log.error(e.toString());
            return null;
        }finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                log.error("httpclient关闭失败");
            }
        }
    }

}
